package wo.jpa.reader.entity;
import java.lang.reflect.Field;

import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import wo.common.exception.WoException;
import wo.common.util.WoUtil;
import wo.jpa.reader.util.JPAReaderConstant;

public class WoJPARelationM2M extends WoJPARelation {
	private final static Logger LOG = LogManager.getLogger(WoJPARelationM2M.class);
	
	private JoinTable joinTable;
	
	/**
	 * true表示source实体维护关系数据，否则target实体维护关系数据
	 */
	private Boolean main = true;
	
	public WoJPARelationM2M (Class<?>sourceClass, Field f) {
		Class<?> targetClass = this.getTargetType(f);
		this.setSource(new WoJPAEntity(sourceClass));
		this.setTarget(new WoJPAEntity(targetClass));
		this.setSourceFieldName(f.getName());
		joinTable = f.getDeclaredAnnotation(JoinTable.class);
		ManyToMany m = f.getDeclaredAnnotation(ManyToMany.class);
		if (joinTable == null) {
			if (WoUtil.isEmpty(m.mappedBy())) {
				throw new WoException (JPAReaderConstant.ERROR_M2M, f.getName());
			}
			Field tf = this.getField(targetClass, m.mappedBy());
			this.setTargetFieldName(tf.getName());
			joinTable = tf.getDeclaredAnnotation(JoinTable.class);
			if (joinTable == null) {
				throw new WoException (JPAReaderConstant.ERROR_JOINTABLE, f.getName());
			}
			main = false;
		}
	}

	public JoinTable getJoinTable() {
		return joinTable;
	}

	public void setJoinTable(JoinTable joinTable) {
		this.joinTable = joinTable;
	}

	public Boolean getMain() {
		return main;
	}

	public void setMain(Boolean main) {
		this.main = main;
	}
	
	/**
	 * 获取关系表关联本对象的列
	 * @return
	 */
	public String getJoinColumnName () {
		if (main) {
			return joinTable.joinColumns()[0].name();
		}
		return joinTable.inverseJoinColumns()[0].name();
	}
	
	/**
	 * 获取关系表关联关联对象的列
	 * @return
	 */
	public String getInverseJoinColumnName () {
		if (!main) {
			return joinTable.joinColumns()[0].name();
		}
		return joinTable.inverseJoinColumns()[0].name();
	}
}
